package com.chexiehui.jc.ui.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.webkit.JavascriptInterface;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.aries.ui.view.radius.RadiusEditText;
import com.aries.ui.view.radius.RadiusTextView;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.SpanUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.adapter.CommVLayoutAdapter;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.base.BasePage;
import com.chexiehui.jc.entity.PostCommentInfo;
import com.chexiehui.jc.entity.PostInfo;
import com.chexiehui.jc.event.GlobalFollowUserEvent;
import com.chexiehui.jc.event.GlobalLikePostEvent;
import com.chexiehui.jc.event.GlobalPostAppraiseEvent;
import com.chexiehui.jc.event.PostCommentChildAppraiseChangeEvent;
import com.chexiehui.jc.event.PostCommentChildLikeChangeEvent;
import com.chexiehui.jc.event.SoftKeyboardShowOrHideEvent;
import com.chexiehui.jc.mvp.forum.ForumDynamicDetailsCovenant;
import com.chexiehui.jc.mvp.forum.ForumDynamicDetailsPresenter;
import com.chexiehui.jc.utils.AppCommonUtil;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.HtmlFormat;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.chexiehui.jc.utils.SoftKeyboardFixerForFullscreen;
import com.chexiehui.jc.widget.CircleImageView;
import com.chexiehui.jc.widget.CommentsView;
import com.chexiehui.jc.widget.CustomXPopupImageLoader;
import com.chexiehui.jc.widget.LoadingLayout;
import com.chexiehui.jc.widget.NonScorllRecyclerView;
import com.chexiehui.jc.widget.ReportBubblePopup;
import com.lxj.xpopup.XPopup;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 帖子详情
 */
public class ForumDynamicDetailsActivity extends BaseMvpActivity<ForumDynamicDetailsPresenter> implements ForumDynamicDetailsCovenant.View {
    @BindView(R.id.iv_person_avatar)
    CircleImageView ivPersonAvatar;
    @BindView(R.id.tv_person_name)
    TextView tvPersonName;
    @BindView(R.id.tv_post_title)
    TextView tvPostTitle;
    @BindView(R.id.tv_post_time)
    TextView tvPostTime;
    @BindView(R.id.rtv_follow_person)
    RadiusTextView rtvFollowPerson;
    //    @BindView(R.id.tv_post_content)
//    TextView tvPostContent;
    @BindView(R.id.wv_post_content)
    WebView wvPostContent;
    @BindView(R.id.iv_forum_image)
    ImageView ivForumImage;
    @BindView(R.id.tv_forum_name)
    TextView tvForumName;
    @BindView(R.id.tv_forum_time)
    TextView tvForumTime;
    @BindView(R.id.tv_goto_forum)
    TextView tvGotoForum;
    @BindView(R.id.recycler)
    NonScorllRecyclerView mRecycler;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.rtv_input_text)
    RadiusTextView rtvInputText;
    @BindView(R.id.tv_post_appraise_count)
    TextView tvPostAppraiseCount;
    @BindView(R.id.tv_post_follow_count)
    TextView tvPostFollowCount;
    @BindView(R.id.tv_post_collection_count)
    TextView tvPostCollectionCount;
    @BindView(R.id.tv_post_share)
    TextView tvPostShare;
    @BindView(R.id.ll_bottom_info_panel)
    LinearLayout llBottomInfoPanel;
    @BindView(R.id.ret_input_content)
    RadiusEditText retInputContent;
    @BindView(R.id.ll_bottom_input_panel)
    LinearLayout llBottomInputPanel;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;

    private DelegateAdapter listAdapter;
    private CommVLayoutAdapter<PostCommentInfo> appraiseAdapter;
    private BasePage<PostCommentInfo> page;
    protected final String HYBRID = "androidH5";
    private String postId;
    private PostInfo postInfo;

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void beforeSetView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            postId = bundle.getString("postId");
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String id = bundle.getString("postId");
            if (!StringUtils.isTrimEmpty(id) && getPostId().equals(id)) {
                return;
            }
            postId = id;
        } else {
            return;
        }
        if (StringUtils.isTrimEmpty(getPostId())) {
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText("暂无车源信息");
            return;
        }
        loadingLayout.setStatus(LoadingLayout.Loading);
        mvpPresenter.getPostInfo();
    }

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("详情")
                .setRightTextDrawable(0);
    }

    private void showReportWheel() {
        new XPopup.Builder(mContext)
                .hasShadowBg(true)
                .isDestroyOnDismiss(true)
                .asBottomList("举报类型",
                        new String[]{"内容不实", "题文不符", "低俗色情", "封面反感",
                                "标题夸大", "其他问题"},
                        (position, text) -> {
                            mvpPresenter.doReport(getPostId(), text);
                        })
                .show();
    }

    private void showRightBubble() {
        new XPopup.Builder(mContext)
                .isDestroyOnDismiss(true)
                .atView(titleBar)
                .hasShadowBg(false)
                .asCustom(new ReportBubblePopup(mContext).setListener(() -> {
                    showReportWheel();
                }))
                .show();
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_forum_dynamic_details;
    }

    @Override
    protected void initView(Bundle var1) {
        SoftKeyboardFixerForFullscreen.assistActivity(this);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setEnableOverScrollDrag(false);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);
        refreshLayout.setEnableOverScrollDrag(true);
        loadingLayout.setOnReloadListener(v -> {
            if (StringUtils.isTrimEmpty(postId)) {
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText("没有找到任何数据");
                return;
            }
            mvpPresenter.getPostInfo();
        });
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mvpPresenter.getPostInfo();
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (page != null && page.getTotalRecordCount() > appraiseAdapter.getData().size()) {
                    mvpPresenter.getCommentList(page.getPageIndex() + 1);
                } else {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }
        });
        retInputContent.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                if (!StringUtils.isTrimEmpty(retInputContent.getText().toString().trim())) {
                    KeyboardUtils.hideSoftInput(retInputContent);
                    mvpPresenter.addComment(getPostId(), retInputContent.getText().toString().trim());
                }
                return true;
            }

            return false;
        });
        VirtualLayoutManager virtualLayoutManager = new VirtualLayoutManager(mContext);
        mRecycler.setLayoutManager(virtualLayoutManager);
        ((SimpleItemAnimator) mRecycler.getItemAnimator()).setSupportsChangeAnimations(false);
        final RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        mRecycler.setRecycledViewPool(viewPool);
        viewPool.setMaxRecycledViews(0, 20);
        listAdapter = new DelegateAdapter(virtualLayoutManager, false);
        mRecycler.setAdapter(listAdapter);

        /*CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setBehavior(new AppBarBehavior());
        ablContainer.setLayoutParams(params);*/

        int dp_10 = SizeUtils.dp2px(10);
        LinearLayoutHelper appraiseHelper = new LinearLayoutHelper(dp_10);
        appraiseHelper.setBgColor(ContextCompat.getColor(mContext, R.color.colorTransparent));
        appraiseHelper.setMargin(0, dp_10, 0, dp_10);
        appraiseAdapter = new CommVLayoutAdapter<PostCommentInfo>(mContext, new ArrayList<>(),
                R.layout.item_forum_dynamic_appraise, appraiseHelper) {
            @Override
            public void convert(ViewHolder holder, int position, PostCommentInfo item) {
                GlideUtil.loadImageViewCrop(mContext, item.getAuthorPhoto(),
                        holder.getView(R.id.iv_item_avatar), R.drawable.shape_circle, R.drawable.shape_circle);
                holder.setText(R.id.tv_item_name, item.getAuthorName());
                holder.setText(R.id.tv_item_car_brand, item.getAuthorRemark());
                holder.setText(R.id.tv_item_time, AppCommonUtil.friendlyTime(item.getCreateTime()));
                holder.setText(R.id.tv_item_reply, item.getReplyCount() > 0 ? item.getReplyCount() + "回复" : "回复");
                holder.setText(R.id.tv_item_appraise_content, item.getContent() + "");
                CommentsView cv_item_reply_list = holder.getView(R.id.cv_item_reply_list);
                TextView rtv_item_zan_count = holder.getView(R.id.rtv_item_zan_count);
                rtv_item_zan_count.setText(item.getLikeCount() + "");
                Drawable drawable1 = getResources().getDrawable(item.isLike() ? R.mipmap.ic_follow_36_s : R.mipmap.ic_follow_48);
                drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
                rtv_item_zan_count.setCompoundDrawables(drawable1, null, null, null);
                rtv_item_zan_count.setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        mvpPresenter.doDianZan(item.getId(), position);
                    }
                });
                cv_item_reply_list.setShowAll(false);
                if (item.getChildList().size() > 0) {
                    cv_item_reply_list.setVisibility(View.VISIBLE);
                    cv_item_reply_list.setList(item.getChildList());
                    cv_item_reply_list.notifyDataSetChanged();
                } else {
                    cv_item_reply_list.setVisibility(View.GONE);
                }
            }
        };
        appraiseAdapter.setItemClickListener((view, position, item) -> {
            startActivity(ForumAppraiseDetailsActivity.class, new BundleBuilder()
                    .putString("postId", postId)
                    .putSerializable("commentId", appraiseAdapter.getData().get(position).getId()).create());
        });
        listAdapter.addAdapter(appraiseAdapter);
        if (StringUtils.isTrimEmpty(postId)) {
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText("没有找到任何数据");
            return;
        }
        initWebView();
        loadingLayout.setStatus(LoadingLayout.Loading);
        mvpPresenter.getPostInfo();
    }

    private void setPostInfo() {
        GlideUtil.loadImageViewCrop(mContext, postInfo.getAuthorPhoto(),
                ivPersonAvatar, R.drawable.shape_circle, R.drawable.shape_circle);
        if (StringUtils.isTrimEmpty(postInfo.getLabel())) {
            tvPostTitle.setText(postInfo.getTitle());
        } else {
            SpanUtils spanUtils = new SpanUtils();
            if (postInfo.getLabel().contains("置顶")) {
                spanUtils.appendImage(R.mipmap.ic_post_zhiding, SpanUtils.ALIGN_BASELINE)
                        .appendSpace(15);
            }
            if (postInfo.getLabel().contains("精华")) {
                spanUtils.appendImage(R.mipmap.ic_post_jinghua, SpanUtils.ALIGN_BASELINE)
                        .appendSpace(15);
            }
            spanUtils.append(postInfo.getTitle())
                    .setForegroundColor(ContextCompat.getColor(mContext, R.color.c_333333))
                    .setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorWhite));
            tvPostTitle.setText(spanUtils.create());
        }
        tvPersonName.setText(postInfo.getAuthorName());
        tvPostTime.setText(AppCommonUtil.friendlyTime(postInfo.getCreateTime()));
        rtvFollowPerson.setVisibility(postInfo.getAuthorId().equals(getUserId()) ? View.GONE : View.VISIBLE);
        rtvFollowPerson.setText(postInfo.isFollow() ? "取消关注" : "关注");
        rtvFollowPerson.setSelected(postInfo.isFollow());
        /*RichText.from(postInfo.getContent())
                .imageClick((imageUrls, position) -> {
                    try {
                        new XPopup.Builder(mContext)
                                .asImageViewer(null, position, (List) imageUrls, null, new CustomXPopupImageLoader())
                                .show();
                    }catch (Exception e){}
                })
                .into(tvPostContent);*/
        tvPostFollowCount.setText(postInfo.getLikenum() + "");
        Drawable drawable1 = getResources().getDrawable(postInfo.isLike() ? R.mipmap.ic_follow_36_s : R.mipmap.ic_follow_48);
        drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
        tvPostFollowCount.setCompoundDrawables(null, drawable1, null, null);
        Drawable drawable2 = getResources().getDrawable(postInfo.isCollection() ? R.mipmap.ic_start_40_s : R.mipmap.ic_start_40);
        drawable2.setBounds(0, 0, drawable2.getMinimumWidth(), drawable2.getMinimumHeight());
        tvPostCollectionCount.setCompoundDrawables(null, drawable2, null, null);
        tvPostAppraiseCount.setText(postInfo.getCommentNum() + "");
        if (!postInfo.getAuthorId().equals(getUserId())) {
            titleBar.setRightTextDrawable(R.mipmap.ic_title_dot_more)
                    .setOnRightTextClickListener(new NoDoubleClickListener() {
                        @Override
                        public void onNoDoubleClick(View view) {
                            showRightBubble();
                        }
                    });
        }
        /*StringBuffer sb = new StringBuffer();
        sb.append("<!DOCTYPE html>");
        sb.append("<html lang=\"en\"><head>");
        sb.append("<meta charset=\"UTF-8\">");
        sb.append("<title></title>");
        sb.append("<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no\" />");
        sb.append("</head><body><div style=\"height:auto!important;height:50px;min-height:50px;\">");
        sb.append(postInfo.getContent());
        sb.append("<div style=\"clear:both;height:0;font-size:1px;line-height:0px;\"></div>");
        sb.append("</div></body></html>");
        System.out.println(sb.toString());*/
        //wvPostContent.loadDataWithBaseURL(null, sb.toString(), "text/html", "utf-8", null);
        /*String content = HtmlFormat.getNewContent(postInfo.getContent());
        wvPostContent.loadUrl("javascript:setContentHtml('" + content + "')");*/
        wvPostContent.loadUrl("file:///android_asset/web/templete.html");
        //wvPostContent.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        /**/
    }

    private void initWebView() {
        WebSettings webSettings = wvPostContent.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setBlockNetworkImage(false);
        webSettings.setBlockNetworkLoads(false);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDisplayZoomControls(false);
        webSettings.setGeolocationEnabled(true);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setSupportZoom(false);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setDisplayZoomControls(false);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        wvPostContent.setVerticalScrollBarEnabled(false);
        wvPostContent.setVerticalScrollbarOverlay(false);
        wvPostContent.setHorizontalScrollBarEnabled(false);
        wvPostContent.setHorizontalScrollbarOverlay(false);
        webSettings.setUserAgentString("Mozilla/5.0 (Linux; U; Android 5.1.1; zh-cn;) AppleWebKit/537.36 (KHTML, like " +
                "Gecko)Version/4.0 Chrome/37.0.0.0 MQQBrowser/6.3 Mobile Safari/537.36");
        wvPostContent.setWebViewClient(new CustomwebViewClient());
        wvPostContent.addJavascriptInterface(new BaseHYBRID(), HYBRID);
        wvPostContent.loadData("加载中...","text/html","UTF-8");
    }

    private class CustomwebViewClient extends WebViewClient {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            LogUtils.e("shouldOverrideUrlLoading", url);
            if (!url.contains("android_asset/web")) {
                return false;
            }
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            LogUtils.e("onPageFinished", url);
//            wvPostContent.loadUrl("javascript:window.androidH5.resize(document.body.getBoundingClientRect().height)");
            addImageClickListener(view);
            /*wvPostContent.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            super.onPageFinished(view, url);
            wvPostContent.postDelayed(() -> {
                if (isFinish()) return;
                wvPostContent.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            }, 500);
            wvPostContent.postDelayed(() -> {
                if (isFinish()) return;
                wvPostContent.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            }, 1000);
            wvPostContent.postDelayed(() -> {
                if (isFinish()) return;
                wvPostContent.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            }, 1500);
            wvPostContent.postDelayed(() -> {
                if (isFinish()) return;
                wvPostContent.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            }, 2000);*/
        }

        private void addImageClickListener(WebView webView) {
            webView.loadUrl("javascript:(function(){" +
                    "var objs = document.getElementsByTagName(\"img\"); " +
                    "for(var i=0;i<objs.length;i++)  " +
                    "{"
                    + "    objs[i].onclick=function()  " +
                    "    {  "
                    + "        window." + HYBRID + ".openImage(this.src);  " +//通过js代码找到标签为img的代码块，设置点击的监听方法与本地的openImage方法进行连接
                    "    }  " +
                    "}" +
                    "})()");
        }
    }

    private void changeWebViewContent() {
        String content = HtmlFormat.getNewContent(postInfo.getContent());
        wvPostContent.loadUrl("javascript:setContentHtml('" + content + "')");
        //wvArticleContent.loadUrl("javascript:window.androidH5.resize(document.body.getBoundingClientRect().height)");
    }

    private class BaseHYBRID {
        @JavascriptInterface
        public void resize(float height) {
            runOnUiThread(() -> {
                if (isFinish()) return;
                LogUtils.e("height", height);
                int h = (int) (height * getResources().getDisplayMetrics().density) + SizeUtils.dp2px(200);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(getResources().getDisplayMetrics().widthPixels, h);
                wvPostContent.setLayoutParams(layoutParams);
            });
        }

        @JavascriptInterface
        public String getContentHtml() {
            String content = HtmlFormat.getNewContent(postInfo.getContent());
            return content;
        }

        @JavascriptInterface
        public void openImage(String imgSrc) {
            runOnUiThread(() -> {
                if (isFinish()) return;
                try {
                    if (!StringUtils.isTrimEmpty(imgSrc)) {
                        List<String> imgList = new ArrayList<>();
                        imgList.add(imgSrc);
                        new XPopup.Builder(mContext)
                                .asImageViewer(null, 0, (List) imgList, null, new CustomXPopupImageLoader())
                                .show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        wvPostContent.stopLoading();
        wvPostContent.removeAllViews();
        wvPostContent.destroy();
        wvPostContent = null;
        super.onDestroy();
    }

    @Subscribe
    public void onSoftKeyboardShowOrHideEvent(SoftKeyboardShowOrHideEvent event) {
        if (event.getState() == 1) {
            llBottomInfoPanel.setVisibility(View.GONE);
            llBottomInputPanel.setVisibility(View.VISIBLE);
        } else {
            llBottomInfoPanel.setVisibility(View.VISIBLE);
            llBottomInputPanel.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.rtv_input_text, R.id.tv_post_follow_count, R.id.tv_post_collection_count,
            R.id.rtv_follow_person, R.id.iv_person_avatar, R.id.tv_person_name})
    public void onViewClicked(View view) {
        if (NoDoubleClickUtils.isDoubleClick()) return;
        switch (view.getId()) {
            case R.id.rtv_input_text:
                retInputContent.setHint("发表评论");
                retInputContent.setText("");
                KeyboardUtils.showSoftInput(retInputContent);
                break;
            case R.id.tv_post_follow_count:
                mvpPresenter.doDianZan(getPostId(), -1);
                break;
            case R.id.tv_post_collection_count:
                mvpPresenter.doShouCang(getPostId());
                break;
            case R.id.rtv_follow_person:
                if (!StringUtils.isTrimEmpty(postInfo.getAuthorId())) {
                    mvpPresenter.doFollowPerson(postInfo.getAuthorId());
                }
                break;
            case R.id.iv_person_avatar:
            case R.id.tv_person_name:
                startActivity(UserInfoActivity.class,
                        new BundleBuilder().putString("userId", postInfo.getAuthorId()).create());
                break;
        }
    }

    @Override
    protected ForumDynamicDetailsPresenter createPresenter() {
        return new ForumDynamicDetailsPresenter(this);
    }

    @Override
    public void onGetPostInfoSuccess(BaseModel<PostInfo> successResult) {
        postInfo = successResult.getData();
        setPostInfo();
        mvpPresenter.getCommentList(1);
    }

    @Override
    public void onGetPostInfoFailure(BaseModel<Object> failureResult) {
        if (failureResult.getResultCode() == Constants.PAGE_DATA_EMPTY) {
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText(failureResult.getResultInfo());
        } else {
            loadingLayout.setStatus(LoadingLayout.Error);
            loadingLayout.setErrorText(failureResult.getResultInfo());
        }
    }

    @Override
    public void onGetPostCommentListSuccess(BaseModel<BasePage<PostCommentInfo>> successResult) {
        page = successResult.getData();
        if (loadingLayout.getStatus() != LoadingLayout.Success) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh();
            appraiseAdapter.getData().clear();
            appraiseAdapter.getData().addAll(page.getItems());
            appraiseAdapter.notifyDataSetChanged();
        } else if (refreshLayout.getState() == RefreshState.Loading) {
            appraiseAdapter.getData().addAll(page.getItems());
            appraiseAdapter.notifyDataSetChanged();
            if (page.getTotalRecordCount() <= appraiseAdapter.getData().size()) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore(true);
            }
        } else {
            refreshLayout.finishRefresh();
            appraiseAdapter.getData().clear();
            appraiseAdapter.getData().addAll(page.getItems());
            appraiseAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onGetPostCommentListFailure(BaseModel<Object> failureResult) {
        if (loadingLayout.getStatus() != LoadingLayout.Success) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (Constants.PAGE_DATA_EMPTY == failureResult.getResultCode()) {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(true);
                if (appraiseAdapter.getData().size() > 0) {
                    appraiseAdapter.getData().clear();
                    appraiseAdapter.notifyDataSetChanged();
                }
            } else if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        } else {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(false);
            }
            if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMore(false);
            }
        }
    }

    @Override
    public void onAddCommentSuccess(BaseModel<PostCommentInfo> successResult) {
        appraiseAdapter.getData().add(successResult.getData());
        appraiseAdapter.notifyDataSetChanged();
        mRecycler.scrollToPosition(appraiseAdapter.getData().size() - 1);
        postInfo.setCommentNum(postInfo.getCommentNum() + 1);
        tvPostAppraiseCount.setText(postInfo.getCommentNum() + "");
        EventBus.getDefault().post(new GlobalPostAppraiseEvent(getPostId(), postInfo.getCommentNum()));
    }

    @Override
    public void onAddCommentFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onDoDianZanSuccess(BaseModel<Integer> successResult) {
        if (successResult.getData() >= 0) {
            PostCommentInfo commentInfo = appraiseAdapter.getData().get(successResult.getData());
            if (commentInfo.isLike()) {
                commentInfo.setLikeCount(commentInfo.getLikeCount() - 1);
            } else {
                commentInfo.setLikeCount(commentInfo.getLikeCount() + 1);
            }
            commentInfo.setLike(!commentInfo.isLike());
            appraiseAdapter.notifyItemChanged(successResult.getData());
        } else {
            if (postInfo.isLike()) {
                postInfo.setLikenum(postInfo.getLikenum() - 1);
            } else {
                postInfo.setLikenum(postInfo.getLikenum() + 1);
            }
            postInfo.setLike(!postInfo.isLike());
            tvPostFollowCount.setText(postInfo.getLikenum() + "");
            Drawable drawable1 = getResources().getDrawable(postInfo.isLike() ? R.mipmap.ic_follow_36_s : R.mipmap.ic_follow_48);
            drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
            tvPostFollowCount.setCompoundDrawables(null, drawable1, null, null);
            EventBus.getDefault().post(new GlobalLikePostEvent(getPostId(), postInfo.isLike()));
        }
    }

    @Override
    public void onDoDianZanFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onDoShouCangSuccess(BaseModel<Object> successResult) {
        if (postInfo.isCollection()) {
            postInfo.setCollectionNum(postInfo.getCollectionNum() - 1);
        } else {
            postInfo.setCollectionNum(postInfo.getCollectionNum() + 1);
        }
        postInfo.setCollection(!postInfo.isCollection());
        Drawable drawable2 = getResources().getDrawable(postInfo.isCollection() ? R.mipmap.ic_start_40_s : R.mipmap.ic_start_40);
        drawable2.setBounds(0, 0, drawable2.getMinimumWidth(), drawable2.getMinimumHeight());
        tvPostCollectionCount.setCompoundDrawables(null, drawable2, null, null);
    }

    @Override
    public void onDoShouCangFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onDoFollowPersonSuccess(BaseModel<Object> successResult) {
        EventBus.getDefault().post(new GlobalFollowUserEvent(postInfo.getAuthorId(), !postInfo.isFollow()));
    }

    @Override
    public void onDoFollowPersonFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onDoReportSuccess(BaseModel<Object> successResult) {
        showToast(successResult.getResultInfo());
    }

    @Override
    public void onDoReportFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public String getPostId() {
        return postId == null ? "" : postId;
    }

    @Subscribe
    public void onPostCommentChildLikeChangeEvent(PostCommentChildLikeChangeEvent event) {
        if (event != null && !StringUtils.isTrimEmpty(event.getCommentId())) {
            for (int i = 0; i < appraiseAdapter.getData().size(); i++) {
                PostCommentInfo commentInfo = appraiseAdapter.getData().get(i);
                if (commentInfo.getId().equals(event.getCommentId())) {
                    if (commentInfo.isLike()) {
                        commentInfo.setLikeCount(commentInfo.getLikeCount() - 1);
                    } else {
                        commentInfo.setLikeCount(commentInfo.getLikeCount() + 1);
                    }
                    commentInfo.setLike(!commentInfo.isLike());
                    appraiseAdapter.notifyItemChanged(i);
                    break;
                }
            }
        }
    }

    @Subscribe
    public void onGlobalFollowUserEvent(GlobalFollowUserEvent event) {
        if (event != null && !StringUtils.isTrimEmpty(event.getUserId())) {
            postInfo.setFollow(event.isFollow());
            rtvFollowPerson.setText(postInfo.isFollow() ? "取消关注" : "关注");
            rtvFollowPerson.setSelected(postInfo.isFollow());
        }
    }

    @Subscribe
    public void onPostCommentChildAppraiseChangeEvent(PostCommentChildAppraiseChangeEvent event) {
        if (event != null && !StringUtils.isTrimEmpty(event.getPostId()) &&
                !StringUtils.isTrimEmpty(event.getCommentId())) {
            if (event.getPostId().equals(getPostId())) {
                postInfo.setCommentNum(postInfo.getCommentNum() + 1);
                tvPostAppraiseCount.setText(postInfo.getCommentNum() + "");
                EventBus.getDefault().post(new GlobalPostAppraiseEvent(getPostId(), postInfo.getCommentNum()));
                for (int i = 0; i < appraiseAdapter.getData().size(); i++) {
                    if (appraiseAdapter.getData().get(i).getId().equals(event.getCommentId())) {
                        appraiseAdapter.getData().get(i).setReplyCount(appraiseAdapter.getData().get(i).getReplyCount() + 1);
                        appraiseAdapter.getData().get(i).getChildList().add(event.getCommentInfo());
                        appraiseAdapter.notifyItemChanged(i);
                        break;
                    }
                }
            }

        }
    }

}
